package com.benmei.weike.service;

import com.benmei.weike.common.Constants;
import com.benmei.weike.dao.*;
import com.benmei.weike.dto.PageResponse;
import com.benmei.weike.dto.mcCourse.*;
import com.benmei.weike.entity.*;
import com.benmei.weike.exception.ClientException;
import com.benmei.weike.exception.ServerException;
import com.benmei.weike.web.vo.mcCourse.McCourseGroupBuyResultResponse;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Peter on 2018/10/8.
 */
@Service
public class McCourseStudentService {
    @Value("${mc.course.group.result.base.url}")
    public String groupResultBaseUrl;
    @Value("${mc.course.detail.base.url}")
    public String detailShareUrl;
    public static final Logger logger = LoggerFactory.getLogger(McCourseStudentService.class);

    @Resource
    private McCourseDao mcCourseDao;
    @Resource
    private McAppointmentDao mcAppointmentDao;
    @Resource
    private McBuyerDao mcBuyerDao;
    @Resource
    private McGroupSettingDao mcGroupSettingDao;
    @Resource
    private McGroupInstanceDao mcGroupInstanceDao;
    @Resource
    private McCourseScheduleSignInDao mcCourseScheduleSignInDao;
    @Resource
    private McCourseScheduleDao mcCourseScheduleDao;
    @Resource
    private TeacherDao teacherDao;
    @Resource
    private StudentDao studentDao;
    @Resource
    private AgoraUidService agoraUidService;
    @Resource
    private ClassRoomEntryLogDao classRoomEntryLogDao;


    public List<Banner> findBanner() {
        return mcCourseDao.findBanner();
    }

    public List<McCourseCategory> findCategory() {
        return mcCourseDao.findCategory();
    }

    public PageResponse<McCourseDto> findMcCourse(StudentFindIndexRequest req, Integer memb_id) {
        PageResponse pageResponse = new PageResponse(req.getPageSize(), req.getCurrentPage());
        RowBounds row = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());
        Long total = mcCourseDao.findMcCourseCount(req.getTitle(), req.getCategory_id());
        pageResponse.setTotal(total);

        List<McCourseDto> courseList = mcCourseDao.findMcCourse(req.getTitle(), req.getCategory_id(), row);
        // 查询是否购买过或预约过此课程
        if (memb_id != null && memb_id != 0) {
            for (McCourseDto dto : courseList) {
                // 先查询预约 ，然后查询购买 ，（有先后顺序，购买优先级高）
                McAppointment mcAppointment = mcAppointmentDao.findAppointmentForStudent(dto.getId(), memb_id);
                if (mcAppointment != null) {
                    dto.setBuy_state(Constants.McCourse.BuyState.booking);
                }

                // 查询购买
                McBuyer mcBuyer = mcBuyerDao.findBuyer(dto.getId(), memb_id);
                if (mcBuyer != null) {
                    dto.setBuy_state(Constants.McCourse.BuyState.buy);
                }
            }
        }
        pageResponse.setData(courseList);
        return pageResponse;
    }


    public McCourseDetailResponse mcCourseDetail(Integer mcCourseId, Integer memb_id) {
        // 查询课程详情
        McCourseDetailResponse response = mcCourseDao.findDetail(mcCourseId);
        if (response == null) {
            throw new ClientException("无效的大班课id:" + mcCourseId);
        }
        response.setGroup_agreement_url("http://file.waijiaojun.com/nativetalk/mc-course/mcCourseAgrementImage@3x.png");// 平台说明图片url,OSS上面的一张图片
        response.setShare_url(detailShareUrl + "/" + mcCourseId);
        response.setShare_title(response.getTitle());
        response.setShare_desc(response.getTitle());
        // 是否支持开团
        McGroupSetting mcGroupSetting = mcGroupSettingDao.findByCourseId(mcCourseId);
        if (mcGroupSetting != null && mcGroupSetting.getEnabled().intValue() == 1) {
            response.setEnable_group(1);
            response.setGroup_max_user(mcGroupSetting.getMax_number());
            // 查询拼团信息
            List<McCourseGroupDto> groups = mcCourseDao.findGroupsByMcCourseId(mcCourseId);
            Collections.sort(groups);
            response.setGroups(groups);
        }

        // 查询是否购买过或预约过此课程
        if (memb_id != null && memb_id != 0) {
            // 先查询预约 ，然后查询购买 ，（有先后顺序，购买优先级高）
            McAppointment mcAppointment = mcAppointmentDao.findAppointmentForStudent(mcCourseId, memb_id);
            if (mcAppointment != null) {
                response.setBuy_state(Constants.McCourse.BuyState.booking);
            }
            // 查询购买
            McBuyer mcBuyer = mcBuyerDao.findBuyer(mcCourseId, memb_id);
            if (mcBuyer != null) {
                response.setBuy_state(Constants.McCourse.BuyState.buy);
                // 是否是团购(在这里只有开团的才返回团购状态：3，参团认为是已购买：2)
                McGroupInstance mcGroupInstance = mcGroupInstanceDao.findByCourseIdAndMembId(mcCourseId, memb_id);
                if (mcGroupInstance != null) {
                    response.setBuy_state(Constants.McCourse.BuyState.groupBuy);
                    response.setGroup_result_url(groupResultBaseUrl + "/" + memb_id + "/" + mcGroupInstance.getId());
                }
            }
        }

        // 查询课表
        List<McCourseScheduleDto> scheduleList = mcCourseDao.findScheduleList(mcCourseId);
        response.setCourse_schedule(scheduleList);

        // 查询评论
        List<McCourseCommentDto> courseCommentDtoList = mcCourseDao.findComments(mcCourseId);
        response.setCourse_comments(courseCommentDtoList);
        response.setServer_current_time(new Date());

        return response;
    }

    // 预约
    public void mcCourseAppointment(Integer mcCourseId, Integer memb_id) {
        McCourse mcCourse = mcCourseDao.findById(mcCourseId);
        // 是否上架
        if (mcCourse.getPutaway().intValue() == Constants.McCourse.Putaway.disable) {
            throw new ClientException("课程已下架");
        }
        // 是否是在预约阶段
        Long currentTime = System.currentTimeMillis();
        if (!(currentTime >= mcCourse.getAppointment_start_time().getTime() && currentTime <= mcCourse.getAppointment_end_time().getTime())) {
            throw new ClientException("该课程不可预约");
        }

        McAppointment mcAppointment = mcAppointmentDao.findAppointmentForStudent(mcCourseId, memb_id);
        if (mcAppointment != null) {
            throw new ClientException("已预约");
        } else {
            McAppointment appointment = new McAppointment();
            appointment.setMc_course_id(mcCourseId);
            appointment.setMemb_id(memb_id);
            mcAppointmentDao.insertSelective(appointment);
        }
    }

    // 学生进入教室
    public McCourseIntoClassRoomResponse intoClassRoom(Integer schedule_id, Integer memb_id) {
        McCourseIntoClassRoomResponse response = new McCourseIntoClassRoomResponse();

        McCourseSchedule schedule = mcCourseScheduleDao.findById(schedule_id);
        if (schedule == null) {
            throw new ClientException("教室不存在，请联系客服（schedule_id:" + schedule_id + "）");
        }

        // 查询老师信息
        Teacher teacher = teacherDao.getById(schedule.getTea_id());
        if (teacher == null) {
            logger.error("老师不存在，teacherId=" + schedule.getTea_id());
            throw new ServerException("进入教室失败：老师不存在，teacherId=" + schedule.getTea_id());
        }

        response.setTeacher_id(teacher.getTea_id());
        response.setTeacher_agora_uid(agoraUidService.getAgoraUid(AgoraUid.Role.teacher, teacher.getTea_id()));
        response.setTeacher_name(teacher.getTea_name());// 查询（没有就创建）老师 agora_uid
        response.setTeacher_avatar(teacher.getTea_head_portrait());

        Student student = studentDao.getById(memb_id);
        if (student == null) {
            logger.error("无效的学生，memb_id=" + memb_id);
            throw new ServerException("无效的学生，memb_id=" + memb_id);
        }
        response.setStudent_id(student.getMemb_id());
        response.setStudent_agora_uid(agoraUidService.getAgoraUid(AgoraUid.Role.student, student.getMemb_id()));
        response.setStudent_name(student.getMemb_name());// 查询（没有就创建）学生 agora_uid
        response.setStudent_avatar(student.getMemb_head_portrait());

        // 签到: 表示学生来上课了，不重复记录
        McCourseScheduleSignIn signIn = mcCourseScheduleSignInDao.find(schedule_id, memb_id);
        if (signIn == null) {
            signIn = new McCourseScheduleSignIn(schedule_id, memb_id);
            mcCourseScheduleSignInDao.insertSelective(signIn);
        }
        // 查询ppt
        List<McCoursewareDto> coursewareList = mcCourseDao.findCourseware(schedule_id);
        response.setCoursewareList(coursewareList);

        // 8. 记录进入教室日志（进出教室，网络状态，通话状态）
        ClassRoomEntryLog entryLog = new ClassRoomEntryLog();
        entryLog.setEvent_date(new Date());
        entryLog.setRoom_id(schedule_id);
        entryLog.setUser_role(Constants.UserRole.student);
        entryLog.setEvent_type(Constants.ClassRoom.EventType.enter);
        entryLog.setCourse_type(Constants.CourseType._1vn);
        classRoomEntryLogDao.insert(entryLog);

        return response;
    }

    // 学生离开教室
    public void leaveClassRoom(Integer mc_course_schedule_id, Integer memb_id) {
        logger.info("离开教室：mc_course_schedule_id=" + mc_course_schedule_id + ", memb_id=" + memb_id);
        // 8. 记录进入教室日志（进出教室，网络状态，通话状态）
        ClassRoomEntryLog entryLog = new ClassRoomEntryLog();
        entryLog.setEvent_date(new Date());
        entryLog.setRoom_id(mc_course_schedule_id);
        entryLog.setUser_role(Constants.UserRole.student);
        entryLog.setEvent_type(Constants.ClassRoom.EventType.leave);
        entryLog.setCourse_type(Constants.CourseType._1vn);
        classRoomEntryLogDao.insert(entryLog);
    }

    // 老师进入教室
    public McCourseIntoClassRoomResponse intoClassRoomForTeacher(Integer schedule_id, Integer tea_id) {
        McCourseIntoClassRoomResponse response = new McCourseIntoClassRoomResponse();

        McCourseSchedule schedule = mcCourseScheduleDao.findById(schedule_id);
        if (schedule == null) {
            throw new ClientException("教室不存在，请联系客服（schedule_id:" + schedule_id + "）");
        }
        // 查询老师信息
        Teacher teacher = teacherDao.getById(tea_id);
        if (teacher == null) {
            logger.error("老师不存在，teacherId=" + schedule.getTea_id());
            throw new ServerException("进入教室失败：老师不存在，teacherId=" + schedule.getTea_id());
        }
        response.setTeacher_id(teacher.getTea_id());
        response.setTeacher_agora_uid(agoraUidService.getAgoraUid(AgoraUid.Role.teacher, teacher.getTea_id()));
        response.setTeacher_name(teacher.getTea_name());
        response.setTeacher_avatar(teacher.getTea_head_portrait());

        // 查询ppt
        List<McCoursewareDto> coursewareList = mcCourseDao.findCourseware(schedule_id);
        response.setCoursewareList(coursewareList);

        ClassRoomEntryLog entryLog = new ClassRoomEntryLog();
        entryLog.setEvent_date(new Date());
        entryLog.setRoom_id(schedule_id);
        entryLog.setUser_role(Constants.UserRole.teacher);
        entryLog.setEvent_type(Constants.ClassRoom.EventType.enter);
        entryLog.setCourse_type(Constants.CourseType._1vn);
        classRoomEntryLogDao.insert(entryLog);
        return response;
    }

    // 老师离开教室
    public void leaveClassRoomForTeacher(Integer mc_course_schedule_id, Integer tea_id) {
        logger.info("老师离开教室：mc_course_schedule_id=" + mc_course_schedule_id + ", tea_id=" + tea_id);
        ClassRoomEntryLog entryLog = new ClassRoomEntryLog();
        entryLog.setEvent_date(new Date());
        entryLog.setRoom_id(mc_course_schedule_id);
        entryLog.setUser_role(Constants.UserRole.teacher);
        entryLog.setEvent_type(Constants.ClassRoom.EventType.leave);
        entryLog.setCourse_type(Constants.CourseType._1vn);
        classRoomEntryLogDao.insert(entryLog);
    }

    // 团购结果，由于该页面需要分享到微信朋友圈，因此带有分享该页面需要的信息：shareTitle，shareUrl，shareImage
    public Map<String, String> findGroupResultUrl(Integer mcCourseId, Integer memb_id) {
        Map<String, String> result = new HashMap<>();
        result.put("groupResultUrl", null);
        result.put("shareTitle", null);
        result.put("shareUrl", null);
        result.put("shareImage", null);
        // 查询购买
        McBuyer mcBuyer = mcBuyerDao.findBuyer(mcCourseId, memb_id);

        // 购买过，团购，并且是自己开团的
        if (mcBuyer != null && mcBuyer.getIs_group_booking().intValue() == 1) {
            McGroupInstance mcGroupInstance = mcGroupInstanceDao.findByCourseIdAndMembId(mcCourseId, memb_id);
            if (mcGroupInstance != null) {
                String groupResultUrl = groupResultBaseUrl + "/" + memb_id + "/" + mcGroupInstance.getId();

                McCourse mc = mcCourseDao.findById(mcCourseId);
                String title = mc.getTitle();
                Double oprice = mc.getPrice().doubleValue();
                McGroupSetting setting = mcGroupSettingDao.findByCourseId(mcCourseId);
                Integer number = setting.getMax_number();
                String groupPrice = setting.getGroup_price().setScale(2, BigDecimal.ROUND_DOWN).toString();


                result.put("groupResultUrl", groupResultUrl);
                result.put("shareTitle", "【" + number + "人拼团￥" + groupPrice + "】" + title + " 原价￥" + oprice);//【3人拼团￥0.01】自然拼读语法 原价￥88
                result.put("shareUrl", groupResultBaseUrl + "/weixinPage/invitation/" + memb_id + "/" + mcGroupInstance.getId());
                result.put("shareImage", "http://file.waijiaojun.com/waijiaojun/waijiaojun_logo_share.png");
            }
        }
        return result;
    }

    public McCourseGroupBuyResultResponse findGroupBuyResult(Integer mc_course_group_id) {
        McCourseGroupBuyResultResponse resultResponse = new McCourseGroupBuyResultResponse();
        McGroupInstance mcGroupInstance = mcGroupInstanceDao.findById(mc_course_group_id);
        resultResponse.setGroupEndTime(mcGroupInstance.getEnd_time());
        resultResponse.setGroupMaxUser(mcGroupInstance.getMax_user_size());
        resultResponse.setRemainGroupUser(mcGroupInstance.getMax_user_size().intValue() - mcGroupInstance.getActual_user_size().intValue());

        McCourse mcCourse = mcCourseDao.findById(mcGroupInstance.getMc_course_id());
        resultResponse.setCourseStartTime(mcCourse.getCourse_start_time());
        resultResponse.setCourseEndTime(mcCourse.getCourse_end_time());
        resultResponse.setCourseSize(mcCourse.getCou_size());
        resultResponse.setCourseName(mcCourse.getTitle());

        McGroupSetting setting = mcGroupSettingDao.findByCourseId(mcGroupInstance.getMc_course_id());
        resultResponse.setGroupPrice(setting.getGroup_price());
        return resultResponse;
    }
}
